// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: tianqiang

#include "coin2/exchange/bit/api_order/native_rest_async_asio_subscriber.h"

namespace coin2::exchange::bit::api_order {

void BitRestAsyncAsioSubscriber::QueryAccountBalance() {
  auto http_context = rest_client()->QueryAccountBalance();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&BitRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BitRestAsyncAsioSubscriber::QueryOpenOrders() {
  auto http_context = rest_client()->QueryOpenOrders();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&BitRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BitRestAsyncAsioSubscriber::QueryHistoryOrders() {
  auto http_context = rest_client()->QueryHistoryOrders();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&BitRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BitRestAsyncAsioSubscriber::QueryFills() {
  auto http_context = rest_client()->QueryFills();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&BitRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BitRestAsyncAsioSubscriber::GenListenKey() {
  auto http_context = rest_client()->GenListenKey();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&BitRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void BitRestAsyncAsioSubscriber::SubscribeAsync() {
  AddPeriodicTask(std::bind(&BitRestAsyncAsioSubscriber::GenListenKey, this), 5, "gen_listen_key");

  AddPeriodicTask(
      std::bind(&BitRestAsyncAsioSubscriber::QueryAccountBalance, this),
      config_.query_account_balance_period_sec(),
      "query_balance");

  AddPeriodicTask(
      std::bind(&BitRestAsyncAsioSubscriber::QueryOpenOrders, this),
      config_.query_open_orders_period_sec(),
      "query_open_orders");

  AddPeriodicTask(
      std::bind(&BitRestAsyncAsioSubscriber::QueryHistoryOrders, this),
      config_.query_cancel_orders_period_sec(),
      "query_history_orders");

  AddPeriodicTask(
      std::bind(&BitRestAsyncAsioSubscriber::QueryFills, this),
      config_.query_fill_period_sec(),
      "query_fills");
}

}  // namespace coin2::exchange::bit::api_order
